package com.youfan.book.controller;

import com.youfan.book.domain.Admin;
import com.youfan.book.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@RequestMapping("/login")
@Controller
public class LoginController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/login")
    public String login() {
        return "login/login";
    }

    @PostMapping("do")
    public String doLogin(String username, String password, Model model, HttpSession httpSession) {
        Admin admin = adminService
                .query()
                .eq("username", username)
                .eq("password", password)
                .one();
        if (admin != null) {
            httpSession.setAttribute("loginName", admin.getUsername());
            return "redirect:/admin/home";
        }
        model.addAttribute("error", "账户或密码错误，请重新登录！");
        return "/login/login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login/login";
    }

}
